<template>
  <!-- 审核表单项 -->
  <div>
    <el-form
      :model="checkForm"
      :rules="rules"
      ref="checkForm"
      label-width="auto"
      label-position="right"
    >
      <el-form-item label="审批流程" prop="checkType">
        <el-select
          v-model="checkForm.checkType"
          placeholder="请选择审批流程"
          style="width: 100%"
          clearable
          @change="changeCheckRule"
        >
          <el-option
            v-for="item in checkRuleList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- 审核表单项 -->
      <div class="selectItem" v-for="(item, index) in initArr" :key="index">
        <el-form-item
          label="审批人"
          required
          v-show="item.type == 1 && item.setType == 4"
        >
          <el-button
            class="button"
            type="primary"
            plain
            icon="el-icon-plus"
            @click="selectCheckUser(item.selectMode, item.nodeUserList)"
            >选择审批人</el-button
          >
          <div class="userTag">
            <!-- v-for="tag in selectedCheckUser" -->
            <el-tag
              v-for="tag in item.nodeUserList"
              :key="tag.name"
              @close="deleteCheckUser(tag.id)"
              closable
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item
          label="抄送人"
          required
          v-show="item.type == 2 && item.userSelectFlag"
        >
          <el-button
            class="button"
            type="primary"
            plain
            icon="el-icon-plus"
            @click="selectSendUser(item.nodeUserList)"
            >选择抄送人</el-button
          >
          <div class="userTag">
            <!--              v-for="tag in selectedSendUser" -->
            <el-tag
              v-for="tag in item.nodeUserList"
              :key="tag.name"
              @close="deleteSendUser(item, tag.id)"
              closable
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </el-form-item>
      </div>
    </el-form>

    <!-- 审批时  要选择的人 -->
    <select-dialog ref="selectDialog"> </select-dialog>
  </div>
</template>
<script>
import selectDialog from './selectUser.vue'
export default {
  name: 'checkFormItem',
  emits: ['setCheckConfig'],
  data () {
    return {
      checkForm: {
        checkType: ''
      },
      checkRuleList: [],//审批规则列表（工作流）
      LeaderInfo: [],
      number: 0,//层数
      initArr: [],//初始化工作流后的数据  用于显示
      checkConfig: {},//审批配置数据
      conditionFlag: false,
      rules: {
        checkType: [
          { required: true, message: '请选择审批流程', trigger: 'change' }
        ],
      }
    }
  },
  components: {
    selectDialog
  },
  mounted () {
    this.getDefaultCheck()
  },
  props: {
    field: {
      type: Object,
      default: () => { return {} }
    },
    checkType: {
      type: Number,
    },
  },
  watch: {
    field: {
      handler: function () {
        if (this.conditionFlag) {
          this.workflowiterators()
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 根据type获取默认审批流程(添加时显示默认审批流程，可根据需求选择其他审批流程)
    async getDefaultCheck () {
      let param = {
        type: this.checkType
      }
      let { data } = await this.$API.workflow.getWorkflowListByType.get(param)
      this.checkRuleList = data
      let exempt = null
      this.checkRuleList.forEach(item => {
        if (item.defaultOrNot == 1) {
          this.checkForm.checkType = item.id
          this.checkConfig = JSON.parse(item.jsonConfig)
          exempt = item.exempt
        }
      })
      this.workflowiterators(this.checkConfig)
      console.log(this.initArr)
      this.$emit('setCheckConfig', this.initArr, exempt)
      // //审核人类型  1指定成员 2主管 3部门 4发起人自选 5发起人自己  7连续多级主管
      // let setType = this.checkConfig.childNode.childNode.setType
      this.getLeaderInfo()
    },
    // 选择其他审批流程
    async changeCheckRule (id) {
      let { data } = await this.$API.workflow.getWorkflowListById.get({ id })
      console.log(data)
      this.checkConfig = JSON.parse(data.jsonConfig)
      this.initArr = []
      this.workflowiterators(this.checkConfig)
      console.log(this.initArr)
      this.$emit('setCheckConfig', this.initArr, data.exempt)
      this.getLeaderInfo()
    },
    workflowiterators (object) {
      if (object.type === 1 || object === 2) {
        this.number++
      }
      object.number = this.number
      if (object.type === 1 || object.type === 2) {
        this.initArr.push(object)
      }
      // 第一次进来是发起人
      if (!object.childNode && !object.conditionNodes) {
        return false
      }
      if (object.conditionNodes) {
        this.conditionFlag = true
        //满足条件
        var isFound = false
        object.conditionNodes.forEach(item => {

          // 1是&&，2是||
          var array = []
          var str = ''
          item.conditionList.forEach(items => {
            str = 'this.field.' + `${items.field}` + items.operator + items.value
            array.push(str)
          })
          var operatorStr = ''
          if (item.conditionMode === 1) {
            operatorStr = array.join('&&')
          } else {
            operatorStr = array.join('||')
          }
          if (isFound) {
            return
          }
          let fn = new Function('return' + `${operatorStr}`)
          if (fn() == false) {
            return
          }
          isFound = true
          this.workflowiterators(item.childNode)
        })
      }

      if (object.childNode) {
        this.workflowiterators(object.childNode)
      }
    },

    // 根据部门id获取主管信息
    async getLeaderInfo () {
      let userInfo = this.$TOOL.data.get('USER_INFO')
      let departmentIds = []
      let grade = ''
      let res = null
      let setType = null
      this.initArr.forEach(async (item) => {

        if (item.type == 1) {
          console.log(item.setType)
          //setType审核人类型  1指定成员 2主管 3部门 4发起人自选 5发起人自己  7连续多级主管
          switch (item.setType) {
            case 1:
              setType = 1
              break
            case 2:
              departmentIds = []
              departmentIds.push(userInfo.departmentId)
              grade = item.directorLevel
              break
            case 3:
              departmentIds = []
              item.nodeRoleList.map(item => {
                departmentIds.push(item.id)
              })
              console.log()
              setType = 3
              break
            case 4:
              setType = 4
              break
            case 5:
              item.nodeUserList.push({
                name: userInfo.userName,
                id: userInfo.departmentId
              })
              setType = 5
              break
            case 7:
              // 7 连续多级主管
              // //0直到最上层主管 1自定义审批终点
              if (item.directorMode == 0) {
                grade = ''
              } else if (item.directorMode == 1) {
                grade = item.directorLevel
              }
              departmentIds.push(userInfo.departmentId)
              break
          }
        }
        // 审核人是指定成员 是自己 或 发起人自选 都不需要获取主管信息
        if (item.setType == 1 || item.setType == 4 || item.setType == 5) {
          return
        }

        if (item.setType == 3) {
          res = await this.$API.workflow.getLeaderByDeptId.get({ departmentId: departmentIds.join(',') })
          res.data.map(d_item => {
            item.nodeUserList.push({
              name: d_item.username,
              id: d_item.id
            })
          })
          return
        }

        if (item.setType == 2 || item.setType == 7) {
          let param = {
            departmentId: departmentIds.join(','),
            grade
          }
          res = await this.$API.workflow.getLeaderById.get(param)
          res.data.map(d_item => {
            item.nodeUserList.push({
              name: d_item.username,
              id: d_item.id
            })
          })
          // this.initArr.forEach(item => {
          //   if (item.type == 1) {
          //     res.data.map(d_item => {
          //       item.nodeUserList.push({
          //         name: d_item.username,
          //         id: d_item.id
          //       })
          //     })
          //   }
          // })
        }
      })
      console.log(this.initArr)


    },

    // 选择审批人
    selectCheckUser (selectMode, list) {
      // selectMode 审核人自选  1自选一个人 2自选多个人
      this.$nextTick(() => {
        //  1审批人 2抄送人
        this.$refs.selectDialog.open(selectMode, 1, list)
      })
    },

    // 选择抄送人
    selectSendUser (list) {
      this.$nextTick(() => {
        //  1审批人 2抄送人
        this.$refs.selectDialog.open(2, 2, list)
      })
    },

    // 删除已选择的审批人
    deleteCheckUser (id) {
      this.selectedCheckUser.forEach((item, index) => {
        if (item.id == id) {
          this.selectedCheckUser.splice(index, 1)
        }
      })
    },
    // 删除已选择的抄送人
    deleteSendUser (data, id) {
      this.initArr.forEach(item => {
        if (item.number == data.number) {
          item.nodeUserList.forEach((t_item, index) => {
            if (t_item.id == id) {
              item.nodeUserList.splice(index, 1)
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.selectItem {
  width: 100%;
}
.el-form {
  padding-left: 30px;
}

.userTag {
  // margin-left: 20px;
}
.button {
  margin-right: 20px;
}
</style>